package cn.huaguo.trigger.http;

import cn.huaguo.domain.user.model.entity.UserEntity;
import cn.huaguo.domain.user.service.IUserService;
import cn.huaguo.trigger.http.dto.UserLoginReqDTO;
import cn.huaguo.trigger.http.dto.UserLoginRespDTO;
import cn.huaguo.types.common.JwtClaimsConstant;
import cn.huaguo.types.enums.ResponseCode;
import cn.huaguo.types.model.Response;
import cn.huaguo.types.properties.JwtProperties;
import cn.huaguo.types.utils.JwtUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description UserController
 * @Author wangQian
 * @Date 2024/5/13
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     *
     * @param userLoginReqDTO
     * @return
     */
    @PostMapping("/login")
    public Response<UserLoginRespDTO> login(@RequestBody UserLoginReqDTO userLoginReqDTO) {
        try {
            log.info("login user: {}", userLoginReqDTO);
            // 微信登录
            UserEntity user = userService.wxLogin(userLoginReqDTO.getCode());

            // 为微信用户生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, user.getOpenid());
            String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

            // 封装返回数据
            Response<UserLoginRespDTO> response = Response.<UserLoginRespDTO>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(UserLoginRespDTO.builder()
                            .openid(user.getOpenid())
                            .token(token)
                            .build())
                    .build();
            log.info("微信登录完成 loginCode: {}, response: {}", userLoginReqDTO.getCode(), JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("登录失败 loginCode: {}, message: {}", userLoginReqDTO.getCode(), e.getMessage());
            return Response.<UserLoginRespDTO>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }

    }
}
